#include "controller_2d.h"

Controller2D::Controller2D(View* view,Model* model)
	: Controller(view,model){
	this->drag.first=false;
}

Controller2D::~Controller2D(){

}

void Controller2D::mouseMotion(float x ,float y){
	if(this->drag.first){
		CurveModel& curve = dynamic_cast<CurveModel&>(*model);
		Point p(x,y);
		curve.movePoint(drag.second,p);
		drag.second=p;
	}
}

void Controller2D::mousePressed(int key,int state,float x ,float y){
	if(state==GLUT_DOWN)
		drag = startDrag(x,y);
}

void Controller2D::notifyViewportLeave(){
	if (drag.first){
		CurveModel& curve = dynamic_cast<CurveModel&>(*model);
		curve.removePoint(drag.second);
		drag=std::pair<bool,Point> (false,Point(0,0));
		curve.calculatePoints();
	}
}

std::pair<bool,Point> Controller2D::startDrag(float x,float y){
	CurveModel& curve = dynamic_cast<CurveModel&>(*model);
	CurveModel::Points::const_iterator it = curve.controlPointBegin();
	for(;it!=curve.controlPointEnd();++it){
		float distance = sqrt(pow((x-it->x1),2) + pow((y-it->x2),2));
		if(distance<dragDistance)
			return std::pair<bool,Point>(true,*it);
	}
	return std::pair<bool,Point>(false,Point());
}

void Controller2D::keyboard(unsigned char key,float x ,float y){
	//TODO
}

void Controller2D::calculatePoints(){
	CurveModel& curve = dynamic_cast<CurveModel&>(*model);
	curve.calculatePoints();
}
